package worker

import (
    "crawler/distribute/config"
    "crawler/engine"
    "crawler/zhenai"
    "errors"
    "log"
)

type Request struct {
    Url  string
    Name string
}

type ParseResult struct {
    Requests []Request
    Items    []interface{}
}

type CrawlService struct {
}

func SerializeRequest(request engine.Request) Request {
    return Request{
        Url:  request.Url,
        Name: request.Parser.Serialize(),
    }
}

func DeserializeRequest(request Request) (engine.Request, error) {
    var parser engine.Parser
    switch request.Name {
    case config.ZhenAiParseCityList:
        parser = engine.NewFuncParser(config.ZhenAiParseCityList, zhenai.ParseCityList)
    case config.ZhenAiParseCity:
        parser = engine.NewFuncParser(config.ZhenAiParseCity, zhenai.ParseCity)
    default:
        return engine.Request{}, errors.New("error request name not known")
    }
    
    return engine.Request{
        Url:    request.Url,
        Parser: parser,
    }, nil
}

func SerializeParseResult(result engine.ParseResult) ParseResult {
    var ret ParseResult
    for _, v := range result.Requests {
        ret.Requests = append(ret.Requests, SerializeRequest(v))
    }
    
    ret.Items = result.Items
    return ret
}

func DeserializeParseResult(result ParseResult) engine.ParseResult {
    var ret engine.ParseResult
    for _, v := range result.Requests {
        req, err := DeserializeRequest(v)
        if err != nil {
            log.Printf("DeserializeRequest error :%s", err.Error())
            continue
        }
        ret.Requests = append(ret.Requests, req)
    }
    ret.Items = result.Items
    return ret
}

func (CrawlService) Process(serializedReq Request, serializedParseResult *ParseResult) error {
    req, err := DeserializeRequest(serializedReq)
    if err != nil {
        log.Printf("DeserializeRequest err:%s", err.Error())
        return err
    }
    
    parseResult := engine.Work(req)
    *serializedParseResult = SerializeParseResult(parseResult)
    return nil
}
